package com.rxt.thermopro.adapter

import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.rxt.ble.BleManager
import com.rxt.thermopro.R
import com.rxt.thermopro.app.AppContext
import com.rxt.thermopro.app.LocalDataDao
import com.rxt.thermopro.bean.DeviceBean
import com.rxt.thermopro.bean.DeviceInfoBean
import com.rxt.thermopro.bean.ProbeBean
import com.rxt.thermopro.bean.ProfileBean
import com.rxt.thermopro.ui.fragment.DeviceListFragment
import kotlinx.android.synthetic.main.item_view_device_list.view.*
import kotlinx.android.synthetic.main.item_view_device_list_bbq.view.*
import kotlinx.android.synthetic.main.item_view_device_list_grill.view.*
import kotlinx.android.synthetic.main.item_view_device_list_tp359.view.*
import kotlinx.android.synthetic.main.item_view_device_list_tp960.view.*

class DeviceListAdapter(var list: MutableList<DeviceBean>) :
    RecyclerView.Adapter<DeviceListAdapter.MyViewHolder>() {

    companion object {
        const val VIEW_TYPE_BBQ = 1
        const val VIEW_TYPE_GRILL = 2
        const val VIEW_TYPE_TP960 = 3
        const val VIEW_TYPE_TP359 = 4
        const val VIEW_TYPE_UNKNOWN = 5
    }

    inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    }

    var presenter: DeviceListFragment.DevicePresenter? = null

    fun setDevicePresenter(presenter: DeviceListFragment.DevicePresenter) {
        this.presenter = presenter
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val itemView = when (viewType) {
            VIEW_TYPE_BBQ -> {
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_view_device_list_bbq, parent, false)
            }
            VIEW_TYPE_GRILL -> {
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_view_device_list_grill, parent, false)
            }
            VIEW_TYPE_TP960 -> {
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_view_device_list_tp960, parent, false)
            }
            VIEW_TYPE_TP359 -> {
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_view_device_list_tp359, parent, false)
            }
            else -> {
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_view_device_list, parent, false)
            }
        }
        return MyViewHolder(itemView)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun getItemViewType(position: Int): Int {
        return list[position].deviceType
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        when (list[position].deviceType) {
            VIEW_TYPE_BBQ -> {
                holder.itemView.tempNum1BBQ.typeface = AppContext.get().getTypeFace()
                holder.itemView.tempNum2BBQ.typeface = AppContext.get().getTypeFace()
                holder.itemView.tempNum3BBQ.typeface = AppContext.get().getTypeFace()
                holder.itemView.tempNum4BBQ.typeface = AppContext.get().getTypeFace()

                holder.itemView.p1BBQ.typeface = AppContext.get().getTypeFace()
                holder.itemView.p2BBQ.typeface = AppContext.get().getTypeFace()
                holder.itemView.p3BBQ.typeface = AppContext.get().getTypeFace()
                holder.itemView.p4BBQ.typeface = AppContext.get().getTypeFace()


                holder.itemView.tempNum1BBQ.text =
                    LocalDataDao.INSTANCE.convertUnitNum(list[position].tempNum1).let {
                        if (it.isEmpty()) {
                            "--"
                        } else {
                            it
                        }
                    }
                holder.itemView.tempNum2BBQ.text =
                    LocalDataDao.INSTANCE.convertUnitNum(list[position].tempNum2).let {
                        if (it.isEmpty()) {
                            "--"
                        } else {
                            it
                        }
                    }
                holder.itemView.tempNum3BBQ.text =
                    LocalDataDao.INSTANCE.convertUnitNum(list[position].tempNum3).let {
                        if (it.isEmpty()) {
                            "--"
                        } else {
                            it
                        }
                    }
                holder.itemView.tempNum4BBQ.text =
                    LocalDataDao.INSTANCE.convertUnitNum(list[position].tempNum4).let {
                        if (it.isEmpty()) {
                            "--"
                        } else {
                            it
                        }
                    }

                holder.itemView.tempUnit1BBQ.text = LocalDataDao.INSTANCE.getTempUnit()
                holder.itemView.tempUnit2BBQ.text = LocalDataDao.INSTANCE.getTempUnit()
                holder.itemView.tempUnit3BBQ.text = LocalDataDao.INSTANCE.getTempUnit()
                holder.itemView.tempUnit4BBQ.text = LocalDataDao.INSTANCE.getTempUnit()

                setBatteryLevel(list[position].batteryLevel, holder.itemView.viewPowerBBQ)
                setSignal(list[position].signalLevel, holder.itemView.viewPhoneBBQ)
                holder.itemView.viewBluetoothBBQ.isSelected = list[position].signalLevel != 100

                holder.itemView.timeLeftValue1BBQ.text = list[position].needTime1
                holder.itemView.timeLeftValue2BBQ.text = list[position].needTime2
                holder.itemView.timeLeftValue3BBQ.text = list[position].needTime3
                holder.itemView.timeLeftValue4BBQ.text = list[position].needTime4

                holder.itemView.viewDeleteBBQ.setOnClickListener {
                    presenter?.deleteDevice(list[position], position)
                }
            }
            VIEW_TYPE_GRILL -> {
                holder.itemView.tempNum1GRill.typeface = AppContext.get().getTypeFace()
                holder.itemView.tempNum2Grill.typeface = AppContext.get().getTypeFace()

                holder.itemView.p1GRILL.typeface = AppContext.get().getTypeFace()
                holder.itemView.p2GRILL.typeface = AppContext.get().getTypeFace()

                holder.itemView.tempNum1GRill.text =
                    LocalDataDao.INSTANCE.convertUnitNum(list[position].tempNum1).let {
                        if (it.isEmpty()) {
                            "--"
                        } else {
                            it
                        }
                    }
                holder.itemView.tempNum2Grill.text =
                    LocalDataDao.INSTANCE.convertUnitNum(list[position].tempNum2).let {
                        if (it.isEmpty()) {
                            "--"
                        } else {
                            it
                        }
                    }
                holder.itemView.tempUnit1GRILL.text = LocalDataDao.INSTANCE.getTempUnit()
                holder.itemView.tempUnit2GRILL.text = LocalDataDao.INSTANCE.getTempUnit()

                setBatteryLevel(list[position].batteryLevel, holder.itemView.viewPowerGrill)
                setSignal(list[position].signalLevel, holder.itemView.viewPhoneGrill)
                holder.itemView.viewBluetoothGrill.isSelected = list[position].signalLevel != 100

                holder.itemView.timeLeftValue1GRILL.text = list[position].needTime1
                holder.itemView.timeLeftValue2Grill.text = list[position].needTime2

                holder.itemView.viewDeleteGrill.setOnClickListener {
                    presenter?.deleteDevice(list[position], position)
                }
            }
            VIEW_TYPE_TP960 -> {
                holder.itemView.tempNum1960.typeface = AppContext.get().getTypeFace()
                holder.itemView.tempNum1960.text =
                    LocalDataDao.INSTANCE.convertUnit(list[position].tempNum1).let {
                        if (it.isEmpty()) {
                            "--" + LocalDataDao.INSTANCE.getTempUnit()
                        } else {
                            it
                        }
                    }
                holder.itemView.targetNum.text =
                    LocalDataDao.INSTANCE.convertUnit(list[position].targetTemp1).let {
                        if (it.isEmpty()) {
                            "--" + LocalDataDao.INSTANCE.getTempUnit()
                        } else {
                            it
                        }
                    }
//                setSignal(list[position].signalLevel, holder.itemView.viewPhone)
                holder.itemView.viewBluetooth960.isSelected = list[position].signalLevel != 100
                if (list[position].probeStatus1 == -1) {
                    holder.itemView.viewBluetooth1.isSelected = list[position].signalLevel != 100
                } else {
                    holder.itemView.viewBluetooth1.isSelected = list[position].probeStatus1 == 1
                }
                holder.itemView.needTime1960.text = list[position].needTime1

                holder.itemView.viewDelete960.setOnClickListener {
                    presenter?.deleteDevice(list[position], position)
                }
            }
            VIEW_TYPE_TP359 -> {
                holder.itemView.temperatureNum359.text =
                    LocalDataDao.INSTANCE.convertUnit(list[position].temperatureNUm).let {
                        if (it.isEmpty()) {
                            "--" + LocalDataDao.INSTANCE.getTempUnit()
                        } else {
                            it
                        }
                    }
                holder.itemView.humidityNum359.text = list[position].humidityNum.let {
                    if (it.isEmpty()) {
                        "--" + "%"
                    } else {
                        "$it%"
                    }
                }
                holder.itemView.heatIndexNum359.text =
                    LocalDataDao.INSTANCE.convertUnit(list[position].heatIndex).let {
                        if (it.isEmpty()) {
                            "--" + LocalDataDao.INSTANCE.getTempUnit()
                        } else {
                            it
                        }
                    }
                setBatteryLevel(list[position].batteryLevel, holder.itemView.viewPower359)
                setSignal(list[position].signalLevel, holder.itemView.viewPhone359)
                holder.itemView.viewBluetooth359.isSelected = list[position].signalLevel != 100

                holder.itemView.viewDelete359.setOnClickListener {
                    presenter?.deleteDevice(list[position], position)
                }
            }
            else -> {
                holder.itemView.viewDelete.setOnClickListener {
                    presenter?.deleteDevice(list[position], position)
                }
            }
        }

        holder.itemView.setOnClickListener {
            presenter?.onItemClick(holder.itemView, position)
        }
    }

    private fun setSignal(level: Int, imageView: ImageView) {
        when (level) {
            in -100..-90 -> {
                imageView.setImageResource(R.drawable.main_not_connected)
            }
            in -90..-80 -> {
                imageView.setImageResource(R.drawable.signal_weak)
            }
            in -80..-70 -> {
                imageView.setImageResource(R.drawable.signal_mid2)
            }
            in -70..-60 -> {
                imageView.setImageResource(R.drawable.signal_mid1)
            }
            in -60..-50 -> {
                imageView.setImageResource(R.drawable.signal_strong2)
            }
            in -50..0 -> {
                imageView.setImageResource(R.drawable.signal_strong1)
            }
            else -> imageView.setImageResource(R.drawable.main_not_connected)
        }
    }

    private fun setBatteryLevel(level: Int, imageView: ImageView) {
        when (level) {
            in 0..1 -> {
                imageView.setImageResource(R.drawable.battery_null)
            }
            in 2..4 -> {
                imageView.setImageResource(R.drawable.battery_low)
            }
            in 5..7 -> {
                imageView.setImageResource(R.drawable.battery_mid)
            }
            in 8..9 -> {
                imageView.setImageResource(R.drawable.battery_full)
            }
            else -> imageView.setImageResource(R.drawable.battery_full)
        }
    }

    fun add(bean: DeviceBean) {
        Log.d("112121->adapter", bean.name + "\n" + bean.address)
        list.add(bean)
        notifyDataSetChanged()
    }

    fun hasBlueDevice(address: String?): Boolean {
        var flag = -1
        list.forEach {
            if (it.address == address) {
                flag = 1
            }
        }
        return flag == 1
    }

    fun refreshTempUnit() {
        notifyDataSetChanged()
    }

    fun updateSignal(address: String, signalInt: Int) {
        list.forEach {
            if (address == it.address) {
                it.signalLevel = signalInt
                it.probeStatus1 = if (signalInt != 100) 1 else 0
            }
        }
        notifyDataSetChanged()
    }

    fun updateTP960TargetTemp(map: HashMap<String, ProfileBean>, targetIndex: Int) {
        list.forEach {
            if (VIEW_TYPE_TP960 == it.deviceType && map.keys.last() == it.address) {
                if (targetIndex == 1) {
                    it.targetTemp1 = map.values.last().highTemperatureNum
                } else {
                    it.targetTemp2 = map.values.last().highTemperatureNum
                }
            }
        }
        notifyDataSetChanged()
    }

    fun updateTP960ProbeStatus(address: String, probeIndex: Int, signalInt: Int) {
        list.forEach {
            if (VIEW_TYPE_TP960 == it.deviceType && address == it.address) {
                if (probeIndex == 0) {
                    it.probeStatus1 = signalInt
                    it.tempNum1 = ""
                } else {
                    it.probeStatus2 = signalInt
                    it.tempNum2 = ""
                }
            }
        }
        notifyDataSetChanged()
    }

    fun getDeviceType(address: String): Int {
        val filterList = list.filter { it.address == address }
        return if (filterList.isNotEmpty()) filterList.last().deviceType else -1
    }

    fun updateNeedTime(map: HashMap<String, String>) {
        println("======>  updateNeedTime  map=$map ")
        var updateIndex = -1
        map.keys.forEach {
            val address = it.split("_")[0]
            val clockIndex = it.split("_")[1].toIntOrNull()?:0
            for (i in 0 until list.size) {
                if (list[i].address == address) {
                    updateIndex = i
                    val needTime = map[it] ?: ""
                    println("======>  updateNeedTime  needTime=$needTime ")
                    when (clockIndex) {
                        0 -> list[i].needTime1 = LocalDataDao.INSTANCE.formatNeedTime(needTime)
                        1 -> list[i].needTime2 = LocalDataDao.INSTANCE.formatNeedTime(needTime)
                        2 -> list[i].needTime3 = LocalDataDao.INSTANCE.formatNeedTime(needTime)
                        3 -> list[i].needTime4 = LocalDataDao.INSTANCE.formatNeedTime(needTime)
                        else -> {

                        }
                    }
                }
            }
        }
        if (updateIndex != -1) {
            notifyDataSetChanged()
        }
    }



    fun updateClockTime(map: HashMap<String, String>, probeIndex: Int) {
        println("======>  updateClockTime  map=$map ")
        var updateIndex = -1
        map.keys.forEach {
            val address = it
            for (i in 0 until list.size) {
                if (list[i].address == address) {
                    updateIndex = i
                    val needTime = map[it] ?: ""
                    when (probeIndex) {
                        0 -> list[i].needTime1 = LocalDataDao.INSTANCE.formatNeedTime(needTime)
                        1 -> list[i].needTime2 = LocalDataDao.INSTANCE.formatNeedTime(needTime)
                        2 -> list[i].needTime3 = LocalDataDao.INSTANCE.formatNeedTime(needTime)
                        3 -> list[i].needTime4 = LocalDataDao.INSTANCE.formatNeedTime(needTime)
                        else -> {

                        }
                    }
                }
            }
        }
        if (updateIndex != -1) {
            notifyDataSetChanged()
        }
    }

    fun getItemByAddress(address: String): DeviceBean {
        val filterList = list.filter { it.address == address }
        return if (filterList.isNotEmpty()) filterList.last() else DeviceBean(
            "",
            "", "", ""
        )
    }

    fun updateBattery(address: String, batteryInt: Int) {
        list.forEach {
            println("===> address=$address   it.address=${it.address}")
            if (address == it.address) {
                it.batteryLevel = batteryInt
            }
        }
        notifyDataSetChanged()
    }

    fun update(itemBean: DeviceBean?) {
        itemBean?.let {
            list.forEach {
                if (it.address == itemBean.address) {
                    it.humidityNum = itemBean.humidityNum
                    it.temperatureNUm = itemBean.temperatureNUm
                    it.tempNum1 = itemBean.tempNum1
                    it.tempNum2 = itemBean.tempNum2
                    it.tempNum3 = itemBean.tempNum3
                    it.tempNum4 = itemBean.tempNum4
                }
            }
        }
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun update(itemBean: DeviceInfoBean) {
        list.forEach {
            if (it.address == itemBean.address) {
                it.batteryLevel = itemBean.electricity.toInt()
            }
        }
        notifyDataSetChanged()
    }

    fun refreshDeviceStatus() {
        val connectedList = BleManager.getInstance().allConnectedDevice
        if (connectedList.isEmpty()) {
            list.forEach { item ->
                item.batteryLevel = -1
                item.signalLevel = 100
                item.tempNum1 = ""
                item.tempNum2 = ""
                item.tempNum3 = ""
                item.tempNum4 = ""
                item.humidityNum = ""
                item.temperatureNUm = ""
                item.probeStatus1 = 0
                item.probeStatus2 = 0
            }
        } else {
            val needConnectList = mutableListOf<DeviceBean>()
            needConnectList.addAll(list)
            connectedList.forEach {
                val list1 = list.filter { item -> item.address == it.mac }
                if (list1.isNotEmpty()) {
                    needConnectList.removeAll(list1)
                }
            }
            needConnectList.forEach {
                list.forEach { item ->
                    println("===> item address=${item.address}   it.address=${it.address}")
                    if (item.address == it.address) {
                        item.batteryLevel = -1
                        item.signalLevel = 100
                        item.tempNum1 = ""
                        item.tempNum2 = ""
                        item.tempNum3 = ""
                        item.tempNum4 = ""
                        item.humidityNum = ""
                        item.temperatureNUm = ""
                        item.probeStatus1 = 0
                        item.probeStatus2 = 0
                    }
                }
            }
        }
        notifyDataSetChanged()
    }

    fun update(itemBean: MutableList<ProbeBean>) {
        list.forEach {
            if (it.address == itemBean.last().address) {
                when (itemBean.size) {
                    1 -> {
                        it.tempNum1 = itemBean[0].temperatureNUm
                        it.temperatureNUm = itemBean[0].temperatureNUm
                        it.humidityNum = itemBean[0].humidityNum
                        it.heatIndex = itemBean[0].heatIndex
                    }
                    2 -> {
                        it.tempNum1 = itemBean[0].temperatureNUm
                        it.tempNum2 = itemBean[1].temperatureNUm
                    }
                    3 -> {
                        it.tempNum1 = itemBean[0].temperatureNUm
                        it.tempNum2 = itemBean[1].temperatureNUm
                        it.tempNum3 = itemBean[2].temperatureNUm
                    }
                    4 -> {
                        it.tempNum1 = itemBean[0].temperatureNUm
                        it.tempNum2 = itemBean[1].temperatureNUm
                        it.tempNum3 = itemBean[2].temperatureNUm
                        it.tempNum4 = itemBean[3].temperatureNUm
                        it.batteryLevel = itemBean[0].batteryNum.toIntOrNull() ?: -1
                    }
                }
            }

        }
        notifyDataSetChanged()
    }

    fun remove(position: Int) {
        list.removeAt(position)
        notifyItemRangeRemoved(position, 1)
        notifyItemRangeChanged(position, itemCount)
    }

    fun remove(address: String) {
        var index = -1
        list.forEach {
            if (it.address == address) {
                index = list.indexOf(it)
                list.removeAt(index)
            }
        }
        if (index != -1) {
            notifyItemRangeRemoved(index, 1)
            notifyItemRangeChanged(index, itemCount)
        }
    }

    fun remove(deviceBean: DeviceBean) {
        var index = -1
        list.forEach {
            if (it.address == deviceBean.address) {
                index = list.indexOf(it)
                list.removeAt(index)
            }
        }
        if (index != -1) {
            notifyItemRangeRemoved(index, 1)
            notifyItemRangeChanged(index, itemCount)
        }
    }

    fun addAll(itList: MutableList<DeviceBean>) {
        list.addAll(itList)
        notifyDataSetChanged()
    }


}